use std::env;
use std::path::PathBuf;
use sysinfo::{System, SystemExt, ProcessorExt, DiskExt};

/// 工具类 `RuntimeUtil` 用于获取运行时系统信息
pub struct RuntimeUtil;

impl RuntimeUtil {
    /// 获取当前工作目录
    ///
    /// # 返回值
    /// 返回包含当前工作目录路径的 `Result<PathBuf, std::io::Error>`
    pub fn current_dir() -> Result<PathBuf, std::io::Error> {
        env::current_dir()
    }

    /// 获取当前可执行文件的路径
    ///
    /// # 返回值
    /// 返回包含当前可执行文件路径的 `Result<PathBuf, std::io::Error>`
    pub fn current_exe() -> Result<PathBuf, std::io::Error> {
        env::current_exe()
    }

    /// 获取环境变量的值
    ///
    /// # 参数
    /// * `key` - 环境变量名
    ///
    /// # 返回值
    /// 返回包含环境变量值的 `Option<String>`
    pub fn get_env(key: &str) -> Option<String> {
        env::var(key).ok()
    }

    /// 获取所有环境变量
    ///
    /// # 返回值
    /// 返回包含所有环境变量的 `Vec<(String, String)>`
    pub fn get_all_envs() -> Vec<(String, String)> {
        env::vars().collect()
    }

    /// 获取系统信息
    ///
    /// # 返回值
    /// 返回包含系统信息的 `System`
    pub fn get_system_info() -> System {
        let mut sys = System::new_all();
        sys.refresh_all();
        sys
    }

    /// 获取操作系统名称
    ///
    /// # 返回值
    /// 返回操作系统名称的 `String`
    pub fn os_name() -> String {
        let sys = Self::get_system_info();
        sys.name().unwrap_or_else(|| "Unknown".to_string())
    }

    /// 获取操作系统版本
    ///
    /// # 返回值
    /// 返回操作系统版本的 `String`
    pub fn os_version() -> String {
        let sys = Self::get_system_info();
        sys.os_version().unwrap_or_else(|| "Unknown".to_string())
    }

    /// 获取主机名称
    ///
    /// # 返回值
    /// 返回主机名称的 `String`
    pub fn hostname() -> String {
        let sys = Self::get_system_info();
        sys.host_name().unwrap_or_else(|| "Unknown".to_string())
    }

    /// 获取CPU信息
    ///
    /// # 返回值
    /// 返回包含CPU信息的 `Vec<String>`
    pub fn cpu_info() -> Vec<String> {
        let sys = Self::get_system_info();
        sys.processors()
            .iter()
            .map(|processor| format!("{}: {} MHz", processor.name(), processor.frequency()))
            .collect()
    }

    /// 获取总内存大小（字节）
    ///
    /// # 返回值
    /// 返回总内存大小的 `u64`
    pub fn total_memory() -> u64 {
        let sys = Self::get_system_info();
        sys.total_memory()
    }

    /// 获取可用内存大小（字节）
    ///
    /// # 返回值
    /// 返回可用内存大小的 `u64`
    pub fn available_memory() -> u64 {
        let sys = Self::get_system_info();
        sys.available_memory()
    }

    /// 获取磁盘信息
    ///
    /// # 返回值
    /// 返回包含磁盘信息的 `Vec<String>`
    pub fn disk_info() -> Vec<String> {
        let sys = Self::get_system_info();
        sys.disks()
            .iter()
            .map(|disk| {
                format!(
                    "{}: {}/{} bytes available",
                    disk.name().to_string_lossy(),
                    disk.available_space(),
                    disk.total_space()
                )
            })
            .collect()
    }

    /// 获取当前进程ID
    ///
    /// # 返回值
    /// 返回当前进程ID的 `u32`
    pub fn current_pid() -> u32 {
        std::process::id()
    }
}

fn main() {
    log::info!("Current directory: {:?}", RuntimeUtil::current_dir());
    log::info!("Current executable: {:?}", RuntimeUtil::current_exe());
    log::info!("Environment variable PATH: {:?}", RuntimeUtil::get_env("PATH"));
    log::info!("All environment variables: {:?}", RuntimeUtil::get_all_envs());
    log::info!("Operating system name: {}", RuntimeUtil::os_name());
    log::info!("Operating system version: {}", RuntimeUtil::os_version());
    log::info!("Hostname: {}", RuntimeUtil::hostname());
    log::info!("CPU info: {:?}", RuntimeUtil::cpu_info());
    log::info!("Total memory: {}", RuntimeUtil::total_memory());
    log::info!("Available memory: {}", RuntimeUtil::available_memory());
    log::info!("Disk info: {:?}", RuntimeUtil::disk_info());
    log::info!("Current process ID: {}", RuntimeUtil::current_pid());
}
